<script setup lang="ts">
import { uploadAPI } from '@/apis/common';
import { createRentAPI, delEnterpriseAPI, deleteRentAPI, getEnterpriseListAPI, getRentBuildListAPI, getRentListAPI, outRentAPI } from '@/apis/enterprise';
import type { Datum, Enterprise, EnterpriseListParams, RentBuilding, RentParams } from '@/types/enterprise';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadFile, type UploadRawFile, type UploadRequestOptions } from 'element-plus';
import { ref, watch } from 'vue';

// 前端自定义的类型，用于展示嵌套表格
interface EnterpriseWithRent extends Enterprise {
  // 合同列表
  rentList: Datum[]
}
const params = ref<EnterpriseListParams>({
  page: 1,
  pageSize: 2,
  name:''
})
const list = ref<Enterprise[]>([])
const total = ref(0)
// 获取企业列表
const getList = async () => {
  const res = await getEnterpriseListAPI(params.value)
  // console.log(res);
  list.value = res.data.rows.map((item) => ({
    ...item,
    rentList: [] // 合同列表默认值，用于嵌套表格渲染
  }))
  total.value = res.data.total
}
getList()

//查询
const onSearch = () => {
  params.value.page = 1
  getList()
}

// 删除
const delEnterprise = (id: string) => {
  if (id.length === 0) return ElMessage.warning({ message: '请选择要删除的企业', type: 'warning' })
  // 删除属于危险操作，需要二次弹窗确认
  ElMessageBox.confirm('确定删除该企业吗？', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 发送请求，删除后端的数据
    await delEnterpriseAPI(id)
    // 轻提示
    ElMessage.success({ message: '删除成功', type: 'success' })
    // 前端重新获取列表
    getList()
  }).catch(() => { })
} 

// 添加合同------------------------
const rentDialogVisible = ref(false)  // 是否显示添加合同弹框

// 初始化租赁表单
const initrentForm = () => {
  return {
    buildingId: undefined,
    contractId: 0,
    contractUrl: '',
    endTime: '',
    enterpriseId: undefined,
    startTime: '',
    type: 0
  }
}

// 添加合同表单
const rentForm = ref<RentParams>(initrentForm())

const buildList = ref<RentBuilding[]>([]) 

// 添加合同 - 打开
const addRent = async (id:number) => {
  rentDialogVisible.value = true
  const res = await getRentBuildListAPI()
  buildList.value = res.data
  rentForm.value.enterpriseId = id
}

// 添加合同 - 表单校验
const rentRules = ref<FormRules<RentParams>>({
  buildingId: [
    { required: true, message: '请选择楼宇', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择租赁日期', trigger: 'blur' }
  ],
  contractId: [
    { required: true, message: '请上传合同文件' }
  ]
})

const fileList =ref<UploadFile[]>([])

// 添加合同 - 关闭
const closeRent = () => {
  rentDialogVisible.value = false
  // 重置表单 + el-form 组件(前端)
  addFormRef.value?.resetFields()
  //主动重置所有数据(后端)
  rentForm.value = initrentForm()
  // 重置时间选择器(前端)
  timeArr.value = []
  // 重置文件列表(前端)
  fileList.value = []
}
// 租赁起止日期
const timeArr = ref<string[]>([])
watch(timeArr, (val) => {
  if (val) {
    rentForm.value.startTime = val[0],
    rentForm.value.endTime = val[1]
  } else {
    rentForm.value.startTime = '',
    rentForm.value.endTime = ''
  }
},{deep:true})

// 通过 disabledDate 函数，来设置禁用掉的日期。
const disabledDate = (time: Date) => {
  // 不能小于今日日期，包含今天 （ 1000 * 60 * 60 * 24 -> 1天的毫秒数 ）
  return time.getTime() < Date.now() - 1000 * 60 * 60 * 24
}

const addFormRef =ref<FormInstance>()

// 上传合同文件
const uploadContract = async (options: UploadRequestOptions) => {
  const fd = new FormData()
  fd.append('file', options.file) // 文件对象
  fd.append('type', 'contract') // 文件类型 
  const res = await uploadAPI(fd)
  // 保存合同附件 url 和 id  用于添加合同
  rentForm.value.contractUrl = res.data.url
  rentForm.value.contractId = res.data.id
  // 校验合同文件是否上传
  addFormRef.value?.validateField('contractId')
  return res.data
}

// 删除上传的文件
const removeUpload = () => {
  rentForm.value.contractUrl = ''
  rentForm.value.contractId = undefined
  addFormRef.value?.validateField('contractId')
}

//上传前校验文件大小
const beforeRemove = (rawFile: UploadRawFile) => {
  const allowSize = 5 * 1024 * 1024 // 5MB
  if (rawFile.size > allowSize) { 
    ElMessage.warning({ message: '文件大小不能超过5MB', type: 'warning' })
    return false
  }
  return true
} 

// 添加合同 - 确定
const addRentConfirm = async () => {
  try {
    // 校验表单
    await addFormRef.value?.validate()
    // 发送请求，添加合同
    await createRentAPI(rentForm.value)
    // 轻提示
    ElMessage.success({ message: '添加合同成功', type: 'success' })
    // 关闭弹框
    closeRent()
  } catch (err) {

  }
}

// 展开行时触发
const onExpandChange = async (row: EnterpriseWithRent) => {
  // 获取企业的合同列表
  const res = await getRentListAPI(row.id)
  // console.log('当前行被展开', res)
  // 把请求回来的数据，直接保存到当前行的企业信息中
  row.rentList = res.data
} 

// 退租
const outRent = (row: Datum) => {
  ElMessageBox.confirm('确定退租吗？', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 发送请求，退租
    await outRentAPI(row.id)
    // 更新当前行的状态 退租按钮变为禁用
    row.status = 3
    // 轻提示
    ElMessage.success({ message: '退租成功', type: 'success' })
  }).catch(() => { })
}

// 删除合同
const deleteRent = (rentRow: Datum, enterPriseRow: EnterpriseWithRent) => {
  ElMessageBox.confirm('确定删除该合同吗？', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 发送请求，删除合同
    await deleteRentAPI(rentRow.id)
    // 删除当前行的合同
    enterPriseRow.rentList = enterPriseRow.rentList.filter((item) => item.id !== rentRow.id)
    // 轻提示
    ElMessage.success({ message: '删除成功', type: 'success' })
  }).catch(() => { })
}
</script>

<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input clearable placeholder="请输入企业名称" class="search-main" v-model="params.name" @clear="onSearch()" />
      <el-button type="primary" @click="onSearch()">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/exterpriseAdd')" v-auth="'park:enterprise:add_edit'">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="list" @expand-change="onExpandChange" row-key="id">
        <!-- type="expand" 显示一个可展开的按钮 -->
        <el-table-column type="expand">
          <template v-slot="{ row }">
            <el-table :data="row.rentList">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态" prop="status">
                <template #default="{ row }">
                  <el-tag v-if="row.status === 0" type="warning">待生效</el-tag>
                  <el-tag v-else-if="row.status === 1" type="success">生效中</el-tag>
                  <el-tag v-else-if="row.status === 2" type="info">已到期</el-tag>
                  <el-tag v-else-if="row.status === 3" type="danger">已退租</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="250">
                <template #default="{ row:rentRow }">
                  <el-button size="small" type="text">续租</el-button>
                  <el-button size="small" type="text" :disabled="rentRow.status === 3" @click="outRent(rentRow)">退租</el-button>
                  <el-button size="small" type="text" :disabled="rentRow.status !== 3" @click="deleteRent(rentRow,row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="120" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作" width="300">
          <template #default="{ row }">
            <el-button size="small" type="primary" link @click="addRent(row.id)">添加合同</el-button>
            <el-button size="small" type="primary" link
              @click="$router.push(`/exterpriseDetail/${row.id}`)">查看</el-button>
            <el-button size="small" type="primary" link @click="$router.push(`/exterpriseAdd/${row.id}`)">编辑</el-button>
            <el-button size="small" type="primary" link @click="delEnterprise(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination :total="total" :page-sizes="[2, 5, 10, 100]" v-model:page-size="params.pageSize"
        v-model:current-page="params.page" @change="getList()" layout="total, prev, pager, next" />
    </div>
    <el-dialog v-model="rentDialogVisible" title="添加合同" width="580">
      <!-- 表单模版 -->
      <div class="form-container">
        <el-form ref="addFormRef" :model="rentForm" :rules="rentRules" label-position="top">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择租赁的楼宇" clearable>
              <el-option v-for="item in buildList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="endTime">
            <el-date-picker v-model="timeArr" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" value-format="YYYY-MM-DD" :disabled-date="disabledDate" />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload v-model:file-list="fileList" accept=".doc, .pdf" :http-request="uploadContract"
              @remove="removeUpload" :before-upload="beforeRemove">
              <el-button size="small" type="primary" plain>上传合同文件</el-button>
              <template #tip>
                <div class="el-upload__tip">支持扩展名：.doc .pdf, 文件大小不超过5M</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="closeRent">取消</el-button>
        <el-button type="primary" @click="addRentConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>